<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!-- 搜索 -->
      <el-input
        v-model="query.fullname"
        clearable
        size="small"
        placeholder="输入名称搜索"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="reloadPage"
      />
      <el-select
        v-model="query.status"
        clearable
        size="small"
        placeholder="状态"
        class="filter-item"
        style="width: 90px"
        @change="reloadPage"
      >
        <el-option
          v-for="item in enabledTypeOptions"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <span>
        <el-button
          class="filter-item"
          size="mini"
          type="success"
          icon="el-icon-search"
          @click="reloadPage"
          >搜索</el-button
        >
        <el-button
          class="filter-item"
          size="mini"
          type="warning"
          icon="el-icon-refresh-left"
          @click="resetReloadPage"
          >重置</el-button
        >
      </span>

      <div class="crud-opts">
        <span class="crud-opts-left">
          <el-button
            v-permission="permission.add"
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="toAdd"
          >
            新增
          </el-button>
          <el-button
            v-permission="permission.edit"
            class="filter-item"
            size="mini"
            type="success"
            icon="el-icon-edit"
            :disabled="selections.length !== 1"
            @click="toEdit(selections[0])"
          >
            修改
          </el-button>
          <el-button
            slot="reference"
            v-permission="permission.del"
            class="filter-item"
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="selections.length === 0"
            @click="toDeleteMy(selections)"
          >
            删除
          </el-button>
        </span>
      </div>
    </div>
    <!--表单组件-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="addShow"
      :title="myTitle"
      width="520px"
    >
      <el-form
        ref="form"
        inline
        :model="myForm"
        :rules="rules"
        size="small"
        label-width="100px"
      >
        <el-form-item label="名称" prop="fullname">
          <el-input v-model="myForm.fullname" style="width: 370px" />
        </el-form-item>
        <el-form-item label="简称" prop="simplename">
          <el-input v-model="myForm.simplename" style="width: 370px" />
        </el-form-item>
        <el-form-item label="排序" prop="num">
          <el-input-number
            v-model.number="myForm.num"
            :min="0"
            :max="999"
            controls-position="right"
            style="width: 370px"
          />
        </el-form-item>
        <el-form-item label="组织编码">
          <el-input v-model="myForm.code" style="width: 370px" />
        </el-form-item>
        <el-form-item label="上级" prop="pid">
          <treeselect
            v-model="myForm.pid"
            :normalizer="normalizer"
            :options="depts"
            style="width: 370px"
            placeholder="选择上级菜单"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 0" label="主数据部门">
          <treeselect
            autoDeselectDescendants
            flat
            v-model="myForm.dataDeptId"
            :normalizer="normalizer"
            :options="depts"
            style="width: 370px"
            multiple
            placeholder="主数据部门"
          />
        </el-form-item>
        <el-form-item label="叶子节点" style="margin-top: 10px">
          <el-radio-group v-model="myForm.isLeaf" style="width: 140px">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公司">
          <el-radio-group v-model="myForm.type" style="width: 140px">
            <el-radio
              v-for="item in typeList"
              :label="item.value"
              :key="item.value"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="myForm.status" style="width: 140px">
            <el-radio
              v-for="item in dict.deptStatus"
              :key="item.id"
              :label="item.code"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="单位类型" prop="companyTypeList" v-if="myForm.type == 1">
          <el-select v-model="myForm.companyTypeList" style="width: 360px" multiple>
            <el-option
              v-for="item in dict.project_company"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >{{ item.name }}</el-option
            >
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="addShow = false"
          >取消</el-button
        >
        <el-button :loading="submitStatus" type="primary" @click="goSubmit"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="loading"
      lazy
      :load="getDeptDatas"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :data="tableData"
      row-key="id"
      @select="selectOne"
      @select-all="selectAll"
    >
      <el-table-column :selectable="checkboxT" type="selection" width="55" />
      <el-table-column label="全称" prop="fullname" show-overflow-tooltip />
      <el-table-column label="简称" prop="simplename" show-overflow-tooltip />
      <el-table-column label="排序" prop="num" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="1"
            inactive-value="0"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            @change="changeEnabled($event, scope.row, scope.row.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-permission="['admin', 'dept:edit', 'dept:del']"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="permission.edit"
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="toEdit(scope.row)"
          />

          <el-button
            v-permission="permission.del"
            slot="reference"
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="toDeleteMy(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->

  </div>
</template>

<script>
import crudDept from "@/api/system/dept";

export default {
  name: "Dept",


  // 设置数据字典
  dicts: ["deptStatus","project_company"],
  data() {
    return {
      loading: true,
      myTitle: "",
      myForm: {},
      selections: [], //选中的数据
      addShow: false, //用来弹窗显示
      page: {
        size: 100,
        total: 0,
        page: 1,
      },
      query: { pid: "0" },
      submitStatus: false,
      tableData: [],

      typeList: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 5,
        },
      ],
      depts: [],
      rules: {
        fullname: [{ required: true, message: "请输入名称", trigger: "blur" }],
        simplename: [{ required: true, message: "请输入简称", trigger: "blur" }],

      },
      permission: {
        add: ["admin", "dept:add"],
        edit: ["admin", "dept:edit"],
        del: ["admin", "dept:del"],
      },
      enabledTypeOptions: [
        { key: "1", display_name: "正常" },
        { key: "0", display_name: "禁用" },
      ],
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    //点击删除
    toDeleteMy(data) {
      this.$confirm("确认要删除吗？")
        .then((_) => {
          let ids = [];
          if (data instanceof Array) {
            data.forEach((val) => {
              ids.push(val.id);
            });
          } else {
            ids.push(data.id);
          }
          crudDept
            .del(ids)
            .then((res) => {
              if (res.code == 200) {
                this.$notify({
                  title: "成功",
                  message: "删除成功",
                  type: "success",
                });
                this.reloadPage();
              } else {
                this.$notify.error({
                  title: "错误",
                  message: "删除失败",
                });
              }
            })
            .catch(() => {
              this.$notify.error({
                title: "错误",
                message: "删除失败",
              });
            });
        })
        .catch((_) => {});
    },
    //显示弹窗赋值
    toEdit(data) {
      this.myForm = data;
      this.myTitle = "编辑组织架构";
      this.addShow = true;
      this.getDepts();
      if (this.myForm.id) {
        this.getDataDepts(this.myForm.id);
      }
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },
    //点击全选触发的方法
    selectAll(e) {
      this.selections = e;
    },
    selectOne(s, r) {
      this.selections = s;
    },
    // 提交前做的操作
    goSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (!this.myForm.hasOwnProperty("children")) {
            delete this.myForm.children;
          }
          if (!this.myForm.hasOwnProperty("hasChildren")) {
            delete this.myForm.hasChildren;
          }
          if (this.myForm.pid !== null && this.myForm.pid === this.myForm.id) {
            this.$message({
              message: "上级不能为空",
              type: "warning",
            });
            return false;
          }
          if (this.myForm.isTop === "1") {
            this.myForm.pid = null;
          }

          this.doSubmit();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //真正的去提交
    doSubmit() {
      this.submitStatus = true;
      crudDept
        .edit(this.myForm)
        .then((res) => {
          this.submitStatus = false;
          if (res.code == 200) {
            if (this.myForm.hasOwnProperty("id") && this.myForm.id) {
              this.$notify({
                title: "成功",
                message: "更新成功",
                type: "success",
              });
            } else {
              this.$notify({
                title: "成功",
                message: "新增成功",
                type: "success",
              });
            }
            //刷新表格
            this.reloadPage();
            this.addShow = false;
          } else {
            this.$notify.error({
              title: "错误",
              message: "更新失败",
            });
          }
        })
        .catch(() => {
          this.submitStatus = false;
          this.$notify.error({
            title: "错误",
            message: "更新失败",
          });
        });
    },

    //显示弹窗
    toAdd() {
      this.addShow = true;
      this.myTitle = "新增组织架构";
      this.myForm = {};
      this.getDepts();
      if (this.myForm.id) {
        this.getDataDepts(this.myForm.id);
      }
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },

    //刷新第一页数据
    reloadPage() {
      this.selections = [];
      this.page.page = 1;
      this.tableData=[]
      this.getData();
    },
    //重置搜索
    resetReloadPage() {
      this.page = {
        size: 10,
        total: 0,
        page: 1,
      };
      this.query = { pid: "0" };
      this.getData();
    },

    //刷新列表
    getData() {
      if (this.query.fullname) {
        this.query.pid = null;
      } else {
        this.query.pid = "0";
      }
      this.query.pageNo = this.page.page-1;
      this.query.pageSize = this.page.size;
      this.loading = true;
      crudDept.getPage(this.query).then((res) => {
        if (res.code == 200) {
          this.loading = false;
          this.tableData = res.data.content;
          this.page.total = res.data.totalElements;

          res.data.content.forEach((o) => {
            if (!o.isLeaf) {
              o.hasChildren = true;
            }
          });
        }
      });
    },

    getDeptDatas(tree, treeNode, resolve) {
      const params = { pid: tree.id };
      crudDept.getDepts(params).then((res) => {
        res.data.forEach((o) => {
          if (!o.isLeaf) {
            o.hasChildren = true;
          }
        });
        resolve(res.data);
      });
    },

    getDepts() {
      crudDept.getTree({ status: "1" }).then((res) => {
        this.depts = res.data;
      });
    },
    getDataDepts(id) {
      crudDept.getDataDepts(id).then((res) => {
        this.myForm.dataDeptId = res.data;
      });
    },

    // 改变状态
    changeEnabled(data, val, index) {
      crudDept
        .edit(val)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
          }
        })
        .catch((err) => {
          let currData = {};
        });
    },
    checkboxT(row, rowIndex) {
      return row.id !== 1;
    },
    normalizer(node) {
      if (!node.pid) {
        node = {
          id: "0",
          name: "请选择菜单",
        };
      }
      if (node.children == null || !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
</style>
